const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const { CampusCardModel, MealCardModel, TransactionModel, userModel, Schoolmodel } = require('../model/model');

// 测试API连接
router.get('/test', async function (req, res) {
    try {
        res.json({
            code: 200,
            message: 'API连接正常',
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        res.json({
            code: 500,
            message: 'API连接失败'
        });
    }
});

// 创建测试用户（仅用于开发测试）
router.post('/create-test-user', async function (req, res) {
    try {
        // 首先查找武汉大学
        let whuSchool = await Schoolmodel.findOne({ name: '武汉大学' });
        
        // 如果武汉大学不存在，创建一个
        if (!whuSchool) {
            whuSchool = new Schoolmodel({
                name: '武汉大学',
                abbreviation: 'WHU',
                studentIdRule: {
                    pattern: '^WHU\\d{7}$',
                    minLength: 10,
                    maxLength: 10,
                    description: '请输入以WHU开头的10位学号'
                }
            });
            await whuSchool.save();
        }

        // 检查测试用户是否已存在
        const existingUser = await userModel.findById('507f1f77bcf86cd799439011');
        if (existingUser) {
            return res.json({
                code: 200,
                message: '测试用户已存在',
                data: {
                    userId: existingUser._id,
                    username: existingUser.username,
                    studentId: existingUser.studentId
                }
            });
        }

        // 创建测试用户
        const testUser = new userModel({
            _id: new mongoose.Types.ObjectId('507f1f77bcf86cd799439011'),
            username: '测试用户',
            studentId: 'WHU2021001',
            schoolId: whuSchool._id,
            password: '123456',
            isAvatarImageSet: false,
            avatarImage: '',
            qianming: '这是一个测试用户',
            isTop: false,
            telp: 13800138000
        });

        await testUser.save();

        res.json({
            code: 200,
            message: '测试用户创建成功',
            data: {
                userId: testUser._id,
                username: testUser.username,
                studentId: testUser.studentId
            }
        });

    } catch (error) {
        console.error('创建测试用户错误:', error);
        res.json({
            code: 500,
            message: '创建测试用户失败'
        });
    }
});

// 绑定校园卡
router.post('/bind', async function (req, res) {
    try {
        const { userId, cardNumber, password } = req.body;

        // 验证必填字段
        if (!userId || !cardNumber || !password) {
            return res.json({
                code: 400,
                message: '请填写所有必填字段'
            });
        }

        // 验证用户是否存在
        const user = await userModel.findById(userId);
        if (!user) {
            return res.json({
                code: 400,
                message: '用户不存在，请先登录或注册'
            });
        }

        // 检查是否已经绑定校园卡
        const existingCard = await CampusCardModel.findOne({ userId });
        if (existingCard) {
            return res.json({
                code: 400,
                message: '您已经绑定了校园卡'
            });
        }

        // 检查卡号是否已被其他用户绑定
        const cardExists = await CampusCardModel.findOne({ cardNumber });
        if (cardExists) {
            return res.json({
                code: 400,
                message: '该卡号已被绑定'
            });
        }

        // 模拟校园卡系统验证（实际项目中应该调用真实的校园卡系统API）
        // 这里简单验证密码长度
        if (password.length < 6) {
            return res.json({
                code: 400,
                message: '校园卡密码错误'
            });
        }

        // 创建校园卡记录
        const campusCard = new CampusCardModel({
            userId,
            cardNumber,
            balance: Math.random() * 500 + 100 // 模拟初始余额
        });

        await campusCard.save();

        // 同时创建对应的饭卡记录，实现绑定
        const mealCard = new MealCardModel({
            userId,
            cardNumber: cardNumber, // 使用相同的卡号
            balance: campusCard.balance // 同步余额
        });

        await mealCard.save();

        res.json({
            code: 200,
            message: '校园卡绑定成功',
            data: {
                cardNumber: campusCard.cardNumber,
                balance: campusCard.balance
            }
        });

    } catch (error) {
        console.error('绑定校园卡错误:', error);
        res.json({
            code: 500,
            message: '绑定失败，请重试'
        });
    }
});

// 获取校园卡信息
router.get('/info/:userId', async function (req, res) {
    try {
        const { userId } = req.params;

        const campusCard = await CampusCardModel.findOne({ userId });
        const mealCard = await MealCardModel.findOne({ userId });

        if (!campusCard) {
            return res.json({
                code: 404,
                message: '未绑定校园卡'
            });
        }

        res.json({
            code: 200,
            message: '获取成功',
            data: {
                campusCard: {
                    cardNumber: campusCard.cardNumber,
                    balance: campusCard.balance,
                    isActive: campusCard.isActive,
                    isLost: campusCard.isLost,
                    lastSyncTime: campusCard.lastSyncTime
                },
                mealCard: mealCard ? {
                    cardNumber: mealCard.cardNumber,
                    balance: mealCard.balance,
                    isActive: mealCard.isActive,
                    lastSyncTime: mealCard.lastSyncTime
                } : null,
                isSynced: campusCard.balance === (mealCard ? mealCard.balance : 0)
            }
        });

    } catch (error) {
        console.error('获取校园卡信息错误:', error);
        res.json({
            code: 500,
            message: '获取失败，请重试'
        });
    }
});

// 校园卡充值
router.post('/recharge', async function (req, res) {
    try {
        const { userId, amount, paymentMethod } = req.body;

        // 验证必填字段
        if (!userId || !amount || amount <= 0) {
            return res.json({
                code: 400,
                message: '充值金额必须大于0'
            });
        }

        const campusCard = await CampusCardModel.findOne({ userId });
        const mealCard = await MealCardModel.findOne({ userId });

        if (!campusCard) {
            return res.json({
                code: 404,
                message: '未绑定校园卡'
            });
        }

        // 记录充值前余额
        const balanceBefore = campusCard.balance;

        // 更新校园卡余额
        campusCard.balance += amount;
        campusCard.lastSyncTime = new Date();
        await campusCard.save();

        // 同步更新饭卡余额
        if (mealCard) {
            mealCard.balance = campusCard.balance;
            mealCard.lastSyncTime = new Date();
            await mealCard.save();
        }

        // 记录交易
        const transaction = new TransactionModel({
            userId,
            cardType: 'campus',
            type: 'recharge',
            amount,
            balanceBefore,
            balanceAfter: campusCard.balance,
            location: '在线充值',
            description: `${paymentMethod || '在线'}充值`
        });

        await transaction.save();

        res.json({
            code: 200,
            message: '充值成功',
            data: {
                cardNumber: campusCard.cardNumber,
                balance: campusCard.balance,
                rechargeAmount: amount
            }
        });

    } catch (error) {
        console.error('充值错误:', error);
        res.json({
            code: 500,
            message: '充值失败，请重试'
        });
    }
});

// 饭卡充值（云缴费）
router.post('/meal-recharge', async function (req, res) {
    try {
        const { userId, amount, paymentMethod } = req.body;

        // 验证必填字段
        if (!userId || !amount || amount <= 0) {
            return res.json({
                code: 400,
                message: '充值金额必须大于0'
            });
        }

        const mealCard = await MealCardModel.findOne({ userId });
        const campusCard = await CampusCardModel.findOne({ userId });

        if (!mealCard) {
            return res.json({
                code: 404,
                message: '未绑定饭卡'
            });
        }

        // 记录充值前余额
        const balanceBefore = mealCard.balance;

        // 更新饭卡余额
        mealCard.balance += amount;
        mealCard.lastSyncTime = new Date();
        await mealCard.save();

        // 同步更新校园卡余额
        if (campusCard) {
            campusCard.balance = mealCard.balance;
            campusCard.lastSyncTime = new Date();
            await campusCard.save();
        }

        // 记录交易
        const transaction = new TransactionModel({
            userId,
            cardType: 'meal',
            type: 'recharge',
            amount,
            balanceBefore,
            balanceAfter: mealCard.balance,
            location: '云缴费充值',
            description: `${paymentMethod || '云缴费'}充值`
        });

        await transaction.save();

        res.json({
            code: 200,
            message: '充值成功',
            data: {
                cardNumber: mealCard.cardNumber,
                balance: mealCard.balance,
                rechargeAmount: amount
            }
        });

    } catch (error) {
        console.error('饭卡充值错误:', error);
        res.json({
            code: 500,
            message: '充值失败，请重试'
        });
    }
});

// 同步余额
router.post('/sync-balance', async function (req, res) {
    try {
        const { userId } = req.body;

        const campusCard = await CampusCardModel.findOne({ userId });
        const mealCard = await MealCardModel.findOne({ userId });

        if (!campusCard || !mealCard) {
            return res.json({
                code: 404,
                message: '未找到绑定的卡片'
            });
        }

        // 以校园卡余额为准进行同步
        const syncBalance = campusCard.balance;
        const balanceBefore = mealCard.balance;

        mealCard.balance = syncBalance;
        mealCard.lastSyncTime = new Date();
        await mealCard.save();

        campusCard.lastSyncTime = new Date();
        await campusCard.save();

        // 如果余额有变化，记录同步交易
        if (balanceBefore !== syncBalance) {
            const transaction = new TransactionModel({
                userId,
                cardType: 'meal',
                type: 'sync',
                amount: syncBalance - balanceBefore,
                balanceBefore,
                balanceAfter: syncBalance,
                location: '系统同步',
                description: '余额同步'
            });

            await transaction.save();
        }

        res.json({
            code: 200,
            message: '余额同步成功',
            data: {
                campusCardBalance: campusCard.balance,
                mealCardBalance: mealCard.balance,
                syncTime: new Date()
            }
        });

    } catch (error) {
        console.error('同步余额错误:', error);
        res.json({
            code: 500,
            message: '同步失败，请重试'
        });
    }
});

// 获取交易记录
router.get('/transactions/:userId', async function (req, res) {
    try {
        const { userId } = req.params;
        const { page = 1, limit = 20, cardType } = req.query;

        const query = { userId };
        if (cardType) {
            query.cardType = cardType;
        }

        const transactions = await TransactionModel.find(query)
            .sort({ transactionTime: -1 })
            .limit(limit * 1)
            .skip((page - 1) * limit);

        const total = await TransactionModel.countDocuments(query);

        res.json({
            code: 200,
            message: '获取成功',
            data: {
                transactions,
                pagination: {
                    page: parseInt(page),
                    limit: parseInt(limit),
                    total,
                    pages: Math.ceil(total / limit)
                }
            }
        });

    } catch (error) {
        console.error('获取交易记录错误:', error);
        res.json({
            code: 500,
            message: '获取失败，请重试'
        });
    }
});

// 解绑校园卡
router.post('/unbind', async function (req, res) {
    try {
        const { userId } = req.body;

        const campusCard = await CampusCardModel.findOne({ userId });
        const mealCard = await MealCardModel.findOne({ userId });

        if (!campusCard) {
            return res.json({
                code: 404,
                message: '未绑定校园卡'
            });
        }

        // 删除校园卡和饭卡记录
        await CampusCardModel.deleteOne({ userId });
        if (mealCard) {
            await MealCardModel.deleteOne({ userId });
        }

        res.json({
            code: 200,
            message: '解绑成功'
        });

    } catch (error) {
        console.error('解绑校园卡错误:', error);
        res.json({
            code: 500,
            message: '解绑失败，请重试'
        });
    }
});

// 挂失/解挂校园卡
router.post('/report-loss', async function (req, res) {
    try {
        const { userId, isLost } = req.body;

        const campusCard = await CampusCardModel.findOne({ userId });

        if (!campusCard) {
            return res.json({
                code: 404,
                message: '未绑定校园卡'
            });
        }

        campusCard.isLost = isLost;
        await campusCard.save();

        res.json({
            code: 200,
            message: isLost ? '挂失成功' : '解挂成功',
            data: {
                cardNumber: campusCard.cardNumber,
                isLost: campusCard.isLost
            }
        });

    } catch (error) {
        console.error('挂失操作错误:', error);
        res.json({
            code: 500,
            message: '操作失败，请重试'
        });
    }
});

module.exports = router;